<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="header">
      <div class="header-left" @click="goBack">
        <Left class="back-icon" />
        <span class="back-text">返回</span>
      </div>
      <h1 class="header-title">我的收藏</h1>
      <div class="header-right">
        <span class="favorites-count">{{ favoritesStore.favoritesCount }}件</span>
      </div>
    </div>

    <!-- 搜索和排序栏 -->
    <div class="search-sort-bar" v-if="favoritesStore.favoritesCount > 0">
      <div class="search-box">
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索收藏商品" 
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="sort-options">
        <div class="sort-item" @click="toggleSortMenu">
          <span>{{ currentSortText }}</span>
          <ArrowRight class="sort-arrow" :class="{ 'rotated': showSortMenu }" />
        </div>
      </div>
    </div>

    <!-- 排序菜单 -->
    <nut-popup v-model:visible="showSortMenu" position="bottom" class="sort-popup">
      <div class="sort-menu">
        <div class="sort-menu-header">
          <h3>排序方式</h3>
          <span class="close-btn" @click="showSortMenu = false">×</span>
        </div>
        <div class="sort-options-list">
          <div 
            class="sort-option" 
            :class="{ active: currentSort === 'time-desc' }"
            @click="selectSort('time-desc')"
          >
            <span>收藏时间（最新）</span>
            <span class="sort-desc">最新收藏的在前面</span>
          </div>
          <div 
            class="sort-option" 
            :class="{ active: currentSort === 'time-asc' }"
            @click="selectSort('time-asc')"
          >
            <span>收藏时间（最早）</span>
            <span class="sort-desc">最早收藏的在前面</span>
          </div>
          <div 
            class="sort-option" 
            :class="{ active: currentSort === 'price-desc' }"
            @click="selectSort('price-desc')"
          >
            <span>价格（从高到低）</span>
            <span class="sort-desc">价格高的在前面</span>
          </div>
          <div 
            class="sort-option" 
            :class="{ active: currentSort === 'price-asc' }"
            @click="selectSort('price-asc')"
          >
            <span>价格（从低到高）</span>
            <span class="sort-desc">价格低的在前面</span>
          </div>
        </div>
      </div>
    </nut-popup>

    <!-- 收藏商品列表 -->
    <div class="favorites-content" v-if="displayedFavorites.length > 0">
      <div class="favorites-list">
        <div 
          class="favorite-item" 
          v-for="item in displayedFavorites" 
          :key="item.id"
        >
          <div class="item-image" @click="goToProduct(item.id)">
            <img :src="item.image" :alt="item.name" />
            <div class="favorite-badge">
              <Heart class="heart-icon" />
            </div>
          </div>
          <div class="item-info">
            <h3 class="item-name" @click="goToProduct(item.id)">{{ item.name }}</h3>
            <p class="item-category">{{ item.category }}</p>
            <div class="item-price">
              <span class="current-price">¥{{ item.currentPrice }}</span>
              <span class="original-price" v-if="item.originalPrice && item.originalPrice !== item.currentPrice">
                ¥{{ item.originalPrice }}
              </span>
            </div>
            <p class="favorite-time">{{ formatTime(item.favoriteTime) }}</p>
          </div>
          <div class="item-actions">
            <button class="action-btn add-to-cart" @click="addToCart(item)">
              <span>加入购物车</span>
            </button>
            <button class="action-btn remove-favorite" @click="removeFavorite(item.id)">
              <span>取消收藏</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <div class="empty-icon">
        <Heart class="heart-icon-large" />
      </div>
      <h3 class="empty-title">暂无收藏商品</h3>
      <p class="empty-desc">去发现更多好物，添加到收藏吧</p>
      <button class="empty-action" @click="goToHome">
        去逛逛
      </button>
    </div>

    <!-- 批量操作栏 -->
    <div class="batch-actions" v-if="favoritesStore.favoritesCount > 0">
      <div class="batch-left">
        <button class="batch-btn clear-all" @click="showClearConfirm = true">
          清空收藏
        </button>
      </div>
      <div class="batch-right">
        <button class="batch-btn add-all-to-cart" @click="addAllToCart">
          全部加入购物车
        </button>
      </div>
    </div>

    <!-- 清空确认弹窗 -->
    <nut-popup v-model:visible="showClearConfirm" position="center" class="confirm-popup">
      <div class="confirm-content">
        <h3 class="confirm-title">确认清空收藏？</h3>
        <p class="confirm-desc">此操作将清空所有收藏商品，无法恢复</p>
        <div class="confirm-actions">
          <button class="confirm-btn cancel" @click="showClearConfirm = false">
            取消
          </button>
          <button class="confirm-btn confirm" @click="clearAllFavorites">
            确认清空
          </button>
        </div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useFavoritesStore } from '@/stores/favorites'
import { useCartStore } from '@/stores/cart'
import { Left, ArrowRight, Heart } from '@nutui/icons-vue'

const router = useRouter()
const favoritesStore = useFavoritesStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showSortMenu = ref(false)
const currentSort = ref('time-desc')
const showClearConfirm = ref(false)

// 计算属性
const displayedFavorites = computed(() => {
  let result = favoritesStore.searchFavorites(searchKeyword.value)
  
  // 应用排序
  switch (currentSort.value) {
    case 'time-desc':
      favoritesStore.sortByTime(false)
      break
    case 'time-asc':
      favoritesStore.sortByTime(true)
      break
    case 'price-desc':
      favoritesStore.sortByPrice(false)
      break
    case 'price-asc':
      favoritesStore.sortByPrice(true)
      break
  }
  
  return result
})

const currentSortText = computed(() => {
  const sortMap = {
    'time-desc': '最新收藏',
    'time-asc': '最早收藏',
    'price-desc': '价格从高到低',
    'price-asc': '价格从低到高'
  }
  return sortMap[currentSort.value] || '最新收藏'
})

// 方法
const goBack = () => {
  router.go(-1)
}

const goToHome = () => {
  router.push('/')
}

const goToProduct = (productId) => {
  router.push(`/product-detail/${productId}`)
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const toggleSortMenu = () => {
  showSortMenu.value = !showSortMenu.value
}

const selectSort = (sortType) => {
  currentSort.value = sortType
  showSortMenu.value = false
}

const addToCart = (item) => {
  try {
    // 构造购物车商品数据
    const cartItem = {
      id: item.id,
      name: item.name,
      currentPrice: item.currentPrice,
      originalPrice: item.originalPrice,
      image: item.image,
      selectedSpec: '默认规格',
      quantity: 1
    }
    
    cartStore.addToCart(cartItem)
    showToast('已添加到购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    showToast('添加失败，请重试')
  }
}

const addAllToCart = () => {
  try {
    let addedCount = 0
    displayedFavorites.value.forEach(item => {
      const cartItem = {
        id: item.id,
        name: item.name,
        currentPrice: item.currentPrice,
        originalPrice: item.originalPrice,
        image: item.image,
        selectedSpec: '默认规格',
        quantity: 1
      }
      
      if (cartStore.addToCart(cartItem)) {
        addedCount++
      }
    })
    
    if (addedCount > 0) {
      showToast(`已添加${addedCount}件商品到购物车`)
    } else {
      showToast('购物车中已有这些商品')
    }
  } catch (error) {
    console.error('批量添加到购物车失败:', error)
    showToast('添加失败，请重试')
  }
}

const removeFavorite = (productId) => {
  if (favoritesStore.removeFromFavorites(productId)) {
    showToast('已取消收藏')
  }
}

const clearAllFavorites = () => {
  favoritesStore.clearAllFavorites()
  showClearConfirm.value = false
  showToast('已清空所有收藏')
}

const formatTime = (timeString) => {
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 2592000000) { // 30天内
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return date.toLocaleDateString()
  }
}

const showToast = (message) => {
  // 尝试使用NutUI的showToast
  if (window.nutui && window.nutui.showToast) {
    window.nutui.showToast(message)
  } else {
    // 创建简单的提示
    const toast = document.createElement('div')
    toast.className = 'simple-toast'
    toast.textContent = message
    document.body.appendChild(toast)
    
    setTimeout(() => {
      document.body.removeChild(toast)
    }, 2000)
  }
}

// 生命周期
onMounted(() => {
  favoritesStore.loadFromLocalStorage()
  favoritesStore.initDefaultFavorites()
})

// 监听搜索关键词变化
watch(searchKeyword, () => {
  // 搜索逻辑已在computed中处理
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.back-icon {
  font-size: 20px;
  color: #333;
}

.back-text {
  font-size: 14px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-right {
  font-size: 14px;
  color: #666;
}

.favorites-count {
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.search-sort-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.search-box {
  flex: 1;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.search-input:focus {
  border-color: #ff4757;
}

.sort-options {
  flex-shrink: 0;
}

.sort-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.sort-arrow {
  font-size: 12px;
  transition: transform 0.3s;
}

.sort-arrow.rotated {
  transform: rotate(90deg);
}

.sort-popup {
  border-radius: 16px 16px 0 0;
}

.sort-menu {
  padding: 20px;
}

.sort-menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.sort-menu-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sort-options-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.sort-option {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.sort-option:hover {
  border-color: #ff4757;
  background: #fff5f5;
}

.sort-option.active {
  border-color: #ff4757;
  background: #fff5f5;
}

.sort-option span:first-child {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.sort-desc {
  font-size: 12px;
  color: #999;
}

.favorites-content {
  padding: 16px;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.favorite-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-image {
  position: relative;
  flex-shrink: 0;
  cursor: pointer;
}

.item-image img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.favorite-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff4757;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.heart-icon {
  font-size: 12px;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-category {
  font-size: 12px;
  color: #999;
  margin: 0 0 8px 0;
}

.item-price {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.favorite-time {
  font-size: 12px;
  color: #ccc;
  margin: 0;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.action-btn.add-to-cart {
  background: #ff4757;
  color: white;
}

.action-btn.add-to-cart:hover {
  background: #e63946;
}

.action-btn.remove-favorite {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.action-btn.remove-favorite:hover {
  background: #e9ecef;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  margin-bottom: 20px;
}

.heart-icon-large {
  font-size: 60px;
  color: #ccc;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.empty-desc {
  font-size: 14px;
  color: #999;
  margin: 0 0 24px 0;
}

.empty-action {
  background: #ff4757;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s;
}

.empty-action:hover {
  background: #e63946;
}

.batch-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.batch-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.batch-btn.clear-all {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.batch-btn.clear-all:hover {
  background: #e9ecef;
}

.batch-btn.add-all-to-cart {
  background: #ff4757;
  color: white;
}

.batch-btn.add-all-to-cart:hover {
  background: #e63946;
}

.confirm-popup {
  border-radius: 16px;
}

.confirm-content {
  padding: 24px;
  text-align: center;
}

.confirm-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.confirm-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 24px 0;
  line-height: 1.5;
}

.confirm-actions {
  display: flex;
  gap: 12px;
}

.confirm-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.confirm-btn.cancel {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e0e0e0;
}

.confirm-btn.cancel:hover {
  background: #e9ecef;
}

.confirm-btn.confirm {
  background: #ff4757;
  color: white;
}

.confirm-btn.confirm:hover {
  background: #e63946;
}

/* 简单提示样式 */
.simple-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 9999;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .favorite-item {
    flex-direction: column;
    gap: 12px;
  }
  
  .item-image {
    align-self: center;
  }
  
  .item-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .batch-actions {
    padding: 12px;
  }
  
  .batch-btn {
    padding: 10px;
    font-size: 13px;
  }
}
</style>
